package service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Iterator;

import library.service.Book;
import library.service.LibraryService;

public class FictionLibraryServiceImpl implements LibraryService {

	private Collection books = new ArrayList();

	public FictionLibraryServiceImpl() {
		books.add(new FictionBookImpl("Yordan Radichkov"));
		books.add(new FictionBookImpl("Erich Kastner"));
		books.add(new FictionBookImpl("John Steinbeck"));
	}

	public Book addBook(Dictionary bookProperties) {

		if (bookProperties == null || bookProperties.isEmpty()) {
			throw new IllegalArgumentException(
					"Null-pointed or empty bookProperties dictionary.");
		}

		Book book = FictionBookFactory.getInstance(bookProperties);

		if (books.contains(book)) {
			throw new IllegalArgumentException(
					"The book is already in the library.");
		}

		books.add(book);
		return book;
	}

	public void removeBook(Book book) {
		if (book == null) {
			throw new IllegalArgumentException("Null-pointed input book");
		}

		boolean deletionResult = books.remove(book);
		if (deletionResult) {
			System.out.println("Book with name " + book.getName()
					+ " is removed.");
		}

	}

	public Book findBookByName(String bookName) {
		if (bookName == null) {
			throw new IllegalArgumentException("illegal input");
		}

		// TODO optimize using Factory and Collections.contains()
		
		Iterator iterator = books.iterator();
		while (iterator.hasNext()) {
			Book book = (Book) iterator.next();
			if (book.getName().equals(bookName)) {
				return book;
			}
		}
		return null;
	}

	public Book[] listBooks() {
		Book[] bookArray = new Book[books.size()];
		bookArray = (Book[]) books.toArray(bookArray);
		return bookArray;
	}
}
